package com.ys.controller.api.finance;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.finance.TcwWanliPrepaymentPooling;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwWanliPrepaymentPoolingService;
import com.ys.service.log.ApiLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.ApiResponse;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 预付款归集明细
 */
@Controller
@RequestMapping("/api/inter/tcwWanliPrepaymentPooling")
public class ApiInterTcwWanliPrepaymentPoolingController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwWanliPrepaymentPoolingController.class);

    @Autowired
    private CommonApiService<TcwWanliPrepaymentPooling> commonApiService;

    @Autowired
    private TcwWanliPrepaymentPoolingService tcwWanliPrepaymentPoolingService;

    @Autowired
    private ApiLogService apiLogService;



    @RequiresPermissions("tcwWanliPrepaymentPooling:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TcwWanliPrepaymentPooling cond,String conditions){

        cond.addLeftJoin("THR_OperateCompanyApply toc ON toc.vgsbm = A.vgsbm")//运营公司
                .addField("toc.vgsjc AS vgsjc,toc.vgsbm AS vgsbm");
        return commonApiService.searchLay(cond);
    }

    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TcwWanliPrepaymentPooling cond,String conditions){

        //查询条件
        String _ys_transactionTimeMin = ConditionUtil.getConditionValue(conditions, "_ys_transactionTimeMin");
        String _ys_transactionTimeMax = ConditionUtil.getConditionValue(conditions, "_ys_transactionTimeMax");
        
        if (_ys_transactionTimeMin != null && _ys_transactionTimeMin.length() > 0) {
        	cond.where("A.TransactionTime >= '" + _ys_transactionTimeMin + "T00:00:00'");
		}
        if (_ys_transactionTimeMax != null && _ys_transactionTimeMax.length() > 0) {
        	cond.where("A.TransactionTime <= '" + _ys_transactionTimeMax + "T23:59:59'");
		}

        cond.addLeftJoin("THR_OperateCompanyApply toc ON toc.vgsbm = A.vgsbm")//运营公司
                .addField("toc.vgsjc AS vgsjc,toc.vgsbm AS vgsbm");
        
        cond.where("A.Id not in (select WanliPrepaymentPoolingId from TCW_WanliReconciliationItem AA LEFT JOIN TCW_WanliReconciliation BB ON BB.Bid = AA.Pbid WHERE BB.EffectStock = 1)");
        cond.where("A.JyCurrencyCode !='CNH'");//归集明细，去除CNH币种的明细

        return commonApiService.searchLay(cond);
    }



    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliPrepaymentPooling cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond.addLeftJoin("THR_OperateCompanyApply toc ON toc.vgsbm = A.vgsbm")//运营公司
                    .addField("toc.vgsjc AS vgsjc,toc.vgsbm AS vgsbm");
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_WanliPrepaymentPooling)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcwWanliPrepaymentPooling> util = new ExportExcelUtils<>(new TcwWanliPrepaymentPooling());
            String toFilePath = util.exportExcel(listData, listField, "万里汇预付款归集明细报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 新数据导入
     */
    @RequiresPermissions("tcwWanliPrepaymentPooling:add")
    @RequestMapping("/add")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            //查询系统数据
            TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("wanli-mid").setKeyTwo("wanli-mid-cs").queryFirst();
            //查询莫程收款平台账号管理
            TcwDepositPlatform tcwDepositPlatform = new TcwDepositPlatform().setMid(tbStaticConfig.getName()).queryFirst();
            ApiResponse apiResponse = tcwWanliPrepaymentPoolingService.inquiryStatementList(tcwDepositPlatform);
            if (apiResponse.getCode() == 500) {
                apiLogService.addApiLog("Wanli", "inquiryStatementList", "ECP_API定时获取万里汇接口获取店铺信息以出错，：", "Mid:" + tcwDepositPlatform.getMid(), apiResponse.getCode(), apiResponse.getMessage());
                return R.error(apiResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     * 批量同步运营公司
     */
    @RequiresPermissions("tcwWanliPrepaymentPooling:tb")
    @RequestMapping("/tbVgsbm")
    @ResponseBody
    public R tbVgsbm(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            return tcwWanliPrepaymentPoolingService.tbVgsbm(idList);
        }catch (Exception e) {
            logger.error("同步运营公司出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改Mid信息
     */
    @RequiresPermissions("tcwWanliPrepaymentPooling:mid")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            return tcwWanliPrepaymentPoolingService.toEdit(params);
        }catch (Exception e) {
            logger.error("同步运营公司出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

}
